package com.lucien.framework.rabbitmq.handler;

import cn.hutool.json.JSONUtil;
import com.lucien.framework.rabbitmq.constants.RabbitCons;
import com.lucien.framework.web.chat.ChatService;
import com.lucien.system.domain.ChatMessage;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author Lucien
 * @Date 2021/6/10 14:58
 * @Version 1.0
 * @Description: 主题队列 处理器
 */

@Component
public class TopicQueueHandler {

    @Autowired
    private ChatService chatService;

    private static final Logger log = LoggerFactory.getLogger(TopicQueueHandler.class);


    @RabbitListener(queues = RabbitCons.TOPIC_QUEUE)
    @RabbitHandler
    public void topicHandleManualAck(Message message, Channel channel) {
        //  如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            byte[] body = message.getBody();
            String msg = new String(body);
            log.info("主题队列" + RabbitCons.TOPIC_QUEUE + "手动ACK，收到消息：{}", msg);
            boolean sendToWebsocket = chatService.sendMsg(msg);
            if (sendToWebsocket) {
                System.out.println("消息处理成功！ 已经推送到websocket！");
                channel.basicAck(deliveryTag, false);
            }
        } catch (IOException e) {
            try {
                // 处理失败,重新压入MQ
                channel.basicRecover();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

}
